<template>
  <el-dialog append-to-body :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="600px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="客户名称" prop="customerName">
        <el-autocomplete
        style="width: 450px"
        class="inline-input"
        v-model="form.customerName"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false" 
        @select="handleSelect"/>
      </el-form-item>
      <el-form-item label="报修地址" >
        <el-input v-model="form.address" style="width: 450px"/>
      </el-form-item>
      <el-form-item label="报修设备" prop="faultDevices">
        <el-select v-model="faultDevices" style="width: 450px;" multiple placeholder="请选择">
          <el-option
            v-for="(item, index) in devices"
            :key="item.eqptname + index"
            :label="item.eqptname"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="故障描述" prop="faultDesc">
        <el-input v-model="form.faultDesc" style="width: 450px;" rows="5" type="textarea"/>
      </el-form-item>
      <el-form-item label="故障图片" >
    <div style="display: inline-block;margin: 0px 2px;width: 450px;">
    <el-upload
      :on-preview="handlePictureCardPreview"
      :before-remove="handleBeforeRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="headers"
      :file-list="fileList"
      :action="imagesUploadApi"
      list-type="picture-card">
      <i class="el-icon-plus"/>
    </el-upload>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" width="100%" alt="">
    </el-dialog>
    </div>
      </el-form-item>
      <el-form-item label="要求到场时间" label-width="113px">
        <el-date-picker
            v-model="form.reqiureTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系人" prop="linker">
        <el-input v-model="form.linker"/>
      </el-form-item>
      <el-form-item label="联系电话" prop="cellphone">
        <el-input v-model="form.cellphone"/>
      </el-form-item>
       <el-form-item label="备注" >
        <el-input v-model="form.notes" style="width: 450px;" rows="5" type="textarea"/>
      </el-form-item>
      <el-form-item label="报修时间" >
        <el-date-picker
            v-model="form.inputTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="录入人" prop="inputOperator">
        <el-input v-model="form.inputOperator"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { add, edit } from '@/api/tAccident'
import { del } from '@/api/picture'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
export default {
  components: { },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    sup_this: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      customers: [],
      devices: [],
      dialog: false,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      pictures: [],
      faultDevices:[],
      loading: false,
      form: {
        id: '',
        customerId: '',
        customerName: '',
        faultDevice: '',
        faultDesc: '',
        faultPicture: '',
        reqiureTime: '',
        address: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        inputTime: '',
        source: '3'
      },
      rules: {
        
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        faultDesc: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
        ],
        linker: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  methods: {
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    querySearch(queryString, cb) {
      //this.getCustomers(queryString);
      const params = {
        customerName:queryString
      }
      request({
        url: 'api/tCustomerInfo',
        method: 'get',
        params
      }).then(res => {
       this.faultDevices = []
       this.devices = []
       this.customers = []
       const content = [].concat(res.content);
       const _this = this
       content.forEach(function(data, index) {
          const customer = { id: data.id,value: data.customerName,address:data.address}
          _this.customers.push(customer)
        })
        cb(this.customers);
      }).catch(err => {
        console.log(err.response.data.message)
      })  
      
    },
    handleSelect(item) {
      this.form.customerId = item.id
      this.form.address = item.address
      this.getEquipment();
    },
    getEquipment(){
      const params = {
        //customerName:queryString
      }
      request({
        url: 'api/tEquipment',
        method: 'get',
        params
      }).then(res => {
       this.devices = res.content;
       console.log(this.devices)
      }).catch(err => {
        console.log(err.response.data.message)
      })  
    },
    cancel() {
      this.resetForm()
      this.fileList = []
      this.pictures = []
      this.dialogVisible = false
      this.dialogImageUrl = ''
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.faultDevices.length === 0) {
            this.$message({
              message: '报修设备不能为空',
              type: 'warning'
            })
          } else {
            this.loading = true
            const _this = this
            const deviceIds = []
            const pictureIds = []
           
            this.faultDevices.forEach(function(data, index) {
              deviceIds.push(data)
            })
            this.form.faultDevice = deviceIds.join(',')
           
            this.pictures.forEach(function(data, index) {
              pictureIds.push(data.id)
            })
            this.form.faultPicture = pictureIds.join(',')
            _this.fileList = []
            if (this.isAdd) {
              this.doAdd()
            } else {
              this.doEdit()
            }
          }
        }else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      this.form.reqiureTime = parseTime(this.form.reqiureTime)

      edit(this.form).then(res => {
        
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.faultDevices=[]
      this.devices = []
      this.form = {
        id: '',
        customerId: '',
        customerName: '',
        faultDevice: '',
        faultDesc: '',
        faultPicture: '',
        reqiureTime: '',
        address: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        inputTime: '',
        source: ''
      }
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.pictures.push({ uid, id })

      console.log(this.pictures)
    },
    handleBeforeRemove(file, fileList) {
      
      const _this = this
      for (let i = 0; i < this.pictures.length; i++) {
        if (this.pictures[i].uid === file.uid || file.id===this.pictures[i].id) {
          del(this.pictures[i].id).then(res => {
            _this.pictures.splice(i,1)
          })
          console.log(_this.pictures)
          return true
        }
      }

      
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>

</style>
